package com.seed.uaa.login.impl;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.query.QueryChain;
import com.seed.core.exception.UserAuthenticateException;
import com.seed.core.pojo.Account;
import com.seed.core.pojo.LoginDTO;
import com.seed.uaa.login.Login;
import com.seed.uaa.util.EncryptUtil;
import com.seed.uaa.util.LoginCheckUtil;
import com.seed.uaa.util.StpKit;
import com.seed.uaa.web.organization.Organization;
import com.seed.uaa.web.user.User;

import static com.seed.uaa.web.organization.table.OrganizationTableDef.ORGANIZATION;
import static com.seed.uaa.web.user.table.UserTableDef.USER;

/**
 * 内部用户编号登录
 */
public class UserCodeLogin implements Login {
    @Override
    public void login(Account account, LoginDTO dto) {
        String code = account.getValue();
        Organization organization = QueryChain.of(Organization.class).where(ORGANIZATION.CODE.eq(code)).one();
        LoginCheckUtil.checkLogin(organization);

        String userId = organization.getManagerId();
        if(StrUtil.isBlank(userId)) {
            throw new UserAuthenticateException("组织无负责人, 不能登录");
        }

        User user = QueryChain.of(User.class).where(USER.ID.eq(userId)).one();
        LoginCheckUtil.checkLogin(user);

        String rawPassword = dto.getPassword();
        String encrypt = EncryptUtil.encrypt(rawPassword, user.getSalt());
        if(!encrypt.equals(user.getPassword())) {
            throw new UserAuthenticateException("用户名或密码错误");
        }

        checkAncestorLogin(organization); //检查祖先用户是否满足登录条件
        StpKit.login(account.getLoginId());
    }

    private void checkAncestorLogin(Organization organization) {
        String parentId = organization.getParentId();
        while (StrUtil.isNotBlank(parentId)) {
            organization = QueryChain.of(Organization.class)
                    .where(ORGANIZATION.ID.eq(parentId))
                    .one();
            LoginCheckUtil.checkAncestorLogin(organization);
            parentId = organization.getParentId();
        }
    }
}
